//
//  WXStickyTabController.m
//  Messenger
//
//  Created by Zhiqiang Bao on 15-1-9.
//
//

#import "WXStickyTabController.h"

@interface WXStickyTabController () <UIGestureRecognizerDelegate>
{
    CGRect bkTabBarRect;
}

@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIView      *tableHeader;
@property (nonatomic, strong) UIView      *tabBar;
@property (nonatomic, strong) UIView      *tabBarHeader;

@end

#define kDefaultTabHeight       44
#define kDefaultTopHeight       44
#define kDefaultHeaderHeight    (kDefaultTabHeight + kDefaultTopHeight)

@implementation WXStickyTabController

- (id)initWithQuery:(NSString*)path query:(NSDictionary*)query
{
    
    self = [self initWithNibName:nil bundle:nil];
    if (self != nil) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)dealloc
{
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
}

- (UIView *)tabBar
{
    return _tabBar;
}

- (UIView *)tabBarHeader
{
    return _tabBarHeader;
}

- (void)setTabBarHeaderHeight:(CGFloat)height
{
    CGRect tabBarFrame = _tabBar.frame;
    CGRect tabBarHeaderFrame = _tabBarHeader.frame;
    CGRect tableHeaderFrame = _tabBarHeader.frame;
    
    CGFloat tableHeaderHeight = height + tabBarFrame.size.height + tabBarHeaderFrame.origin.y;
    tableHeaderFrame.size.height = tableHeaderHeight;
    _tableHeader.frame = tableHeaderFrame;
    
    tabBarHeaderFrame.size.height = height;
    _tabBarHeader.frame = tabBarHeaderFrame;
    
    tabBarFrame.origin.y = height + tabBarHeaderFrame.origin.y;
    bkTabBarRect = tabBarFrame;
    
    if (_tabBar.superview == self.view) {
        tabBarFrame.origin = CGPointZero;
    }
    _tabBar.frame = tabBarFrame;
    
    self.tableView.tableHeaderView = nil;
    self.tableView.tableHeaderView = self.tableHeader;
}

- (void)setTabBarHeight:(CGFloat)height
{
    CGRect tabBarFrame = _tabBar.frame;
    CGRect tabBarHeaderFrame = _tabBarHeader.frame;
    CGRect tableHeaderFrame = _tableHeader.frame;
    
    CGFloat tableHeaderHeight = height + tabBarHeaderFrame.size.height + tabBarHeaderFrame.origin.y;
    tableHeaderFrame.size.height = tableHeaderHeight;
    _tableHeader.frame = tableHeaderFrame;
    
    tabBarFrame.origin.y = tabBarHeaderFrame.size.height + tabBarHeaderFrame.origin.y;
    tabBarFrame.size.height = height;
    bkTabBarRect = tabBarFrame;
    
    if (_tabBar.superview == self.view) {
        tabBarFrame.origin = CGPointZero;
    }
    _tabBar.frame = tabBarFrame;
    
    self.tableView.tableHeaderView = nil;
    self.tableView.tableHeaderView = self.tableHeader;
}

- (void)initLayout
{
    CGFloat width = [[UIScreen mainScreen] bounds].size.width;
    
    self.tableHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, kDefaultHeaderHeight)];
    self.tabBarHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, kDefaultTopHeight)];
    self.tabBar = [[UIView alloc] initWithFrame:CGRectMake(0, kDefaultTopHeight, width, kDefaultTabHeight)];
    [self.tableHeader addSubview:self.tabBarHeader];
    [self.tableHeader addSubview:self.tabBar];
    
    self.tableView.tableHeaderView = nil;
    self.tableView.tableHeaderView = self.tableHeader;
    
    bkTabBarRect = _tabBar.frame;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    [self initLayout];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 10;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ContentCell";
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
    cell.textLabel.text = [@"test" stringByAppendingFormat:@"%d",indexPath.row];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _tableView) {
        if (scrollView.contentOffset.y >= _tabBarHeader.frame.size.height + _tabBarHeader.frame.origin.y) {
            if ( _tabBar.superview != self.view) {
                CGRect frame = _tabBar.frame;
                frame.origin = CGPointZero;
                _tabBar.frame = frame;
                
                [_tabBar removeFromSuperview];
                [self.view addSubview:_tabBar];
            }
        }else{
            if ( _tabBar.superview == self.view) {
                _tabBar.frame = bkTabBarRect;
                
                [_tabBar removeFromSuperview];
                [_tableHeader addSubview:_tabBar];
            }
        }
    }
}


// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    [self setTabBarHeight:indexPath.row * 4];
    [self setTabBarHeaderHeight:indexPath.row * 3];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
